<?php
use kartik\select2\Select2;
use kartik\touchspin\TouchSpin;
use app\modules\Product\models\ProductRoomPrice;
use app\modules\Product\models\ProductRoom;
use app\modules\Product\models\ProductFlight;
use app\modules\Product\models\ProductGroup;
use app\modules\Product\models\ProductVisit;
use app\modules\Order\models\OrderRoom;

// 获取有库存的舱房信息
$data = [];
$stock = $model->product->stock;
$id =  $model->product->id;

if($stock == 2){// 自定义库存格式
	$room = json_decode($model->product->rooms, true);
	if($room){
		foreach($room as $key=>$m){
			//  获取已售数量
			$sell_num = OrderRoom::find()->where(['product_id'=>$model->product_id, 'room_id'=>$key, 'status'=>1, 'stock'=>1])->count();

			if(($m['num']-$sell_num) >0){
				$data[$key] = sprintf("%s | 价格 %s/%s (%d)", $m['name'], $m['price'], $m['inside_price'], ($m['num']-$sell_num)); 	
			}
		}
	}
}else{ //标准库存格式
	$room = ProductRoom::find()->where(['product_id'=> $model->product_id] )->andWhere(['>', 'num', 0])->all(); 

	foreach($room as $key=>$m){ // productRoom
		// 查询已售出库存数
		$sell_stock = 0;

		$num = OrderRoom::find()->where(['product_id'=>$m->product_id, 'room_id'=>$m->id, 'status'=>1, 'stock'=>1])->count();  // 获取已售出库存数
		if(($m->num-$num) >0){
			$n = $m->num - $num;

	    	$key = sprintf("%s %s ", Yii::$app->params['room_type'][$m->room->type], $m->room->code);

	    	$data[$key][$m->id] = sprintf("%s %s ,%s 人间  |  价格 %s/%s | (%s)", Yii::$app->params['room_type'][$m->room->type], $m->room->code, $m->people , $m->price, $m->inside_price, $n);
		}
	}
}
?>

<input type='hidden' id="room-click-num" value=1>
<input type='hidden' id="product-id" value="<?= $id ?>">
<input type='hidden' id="relady-room-num" value=0>

<div class="order-change row change-room" style="margin-bottom:5px;">
    <div class="col-md-8 _change1">
        <?= Select2::widget([
                //'name'  => 'room[1][id]',
                'name'  => 'change_room',
                'data'  => $data,
                'options' => ['placeholder' => Yii::t('app.order', 'Change Room'), 'class'=>'_change_room' ],
                'pluginOptions' => ['allowClear' => true],
				'pluginEvents' => [
					'change' => "function(){
									var room_id  = $(this).val();
									var product_id = $('#product-id').val();

									$.get('/order/order/product-room-stock', {product_id: product_id, room_id: room_id}, 
										function(data){
											//console.log(data); 
											// 获取当前房型实际剩余数量
											$('#change_room_num').trigger('touchspin.updatesettings', {max: data}); 
										});
								}",
				],
            ]);
        ?>
    </div>

    <div class="col-md-2 set_room_num" >
		<?php
			echo TouchSpin::widget([
				'name'   => 'change_room_num',
				'id'   => 'change_room_num',
				'value' => 1,
				'options' => ['class' => 'change_room_num', 'style'=>'padding:0px;'],
				'pluginOptions' => [
					'verticalbuttons' => true,
					'verticalupclass' => 'glyphicon glyphicon-plus',
					'verticaldownclass' => 'glyphicon glyphicon-minus',
					'min' => 1,
					'max' => 100,
				],
			]);
		?>
    </div>

	<div class="col-md-2 "><button type="button" class="btn btn-default" id="room-add">添加</button></div>
	<div class="col-md-12"><hr></div>
</div>
<div id="show-chage-text">
	已选择  0 间
</div>
<div id="show-chage-text">
<hr> <!--  todo  判断是否显示佣金金额 -->
   	<!-- ?= $form->field($model, 'commiss_price')->label("佣金金额")->textInput() ? -->
</div>

<?php app\components\JsBlock::begin() ?>
<script type="text/javascript">
     var data = <?php echo json_encode($data) ?>;
	 var type = <?php echo json_encode($stock) ?>;

    $("#room-add").click(function(){
		var count = $(this).parent().siblings(".set_room_num").children("div").children(".change_room_num").val();
		var room  = $(this).parent().siblings("._change1").children("._change_room").val();// 房间ID号
		var name  = $(this).parent().siblings("._change1").children("._change_room").find("option:selected").text();// 房间名称


		// 匹配到人数
		if(room){
		
			var star = name.substr(0, name.indexOf("|"));
			var p = name.substr(name.indexOf(",")+1, 1);
			var people = p.replace(/[^0-9]/ig,"");

        	var click = $("#relady-room-num").val(); //  现已选择房间的数量

        	var num = parseInt(click) + parseInt(count);
        	$("#relady-room-num").val(num);
			//console.log(count);	// 待添加数量	//console.log(click);	// 现已选择房间的数量	//console.log(num);	// 总数

			for(var i=1; i<= count; i++){

				addItem(parseInt(click)+parseInt(i), room, people, name);
			}	

			//console.log(room);
			room_num();
		}
    });

	function addItem(num, room_id, people, name){ //{{{
        var html  = '<div class="order-change row change-room new-room" data-id='+room_id+' data-val="'+name+'" style="margin-bottom:15px;">';

		var s1 = (type ==1) ? 'col-md-9' : 'col-md-6';
        html += '<div class="'+ s1 +' _change1">';
        html += '<select class="_change_room select2-add form-control" name="room['+num+'][id]">';

		if(type == 2){ //海外航线
        	$.each(data, function(key, item){
			   var chk = '';
			   if(room_id){
			   		if(key == room_id){
			   			chk = 'selected';	
					}
			   }
			   
        	   html += '<option value="'+key+'"  '+chk+' >'+ item +'</option>';
        	});
		}else{
	       	$.each(data, function(key, item){
        	   html += '<optgroup label="'+key+'">';
        	   $.each(item, function(k, i){
			   		var chk = '';
			   		if(room_id){
			   			if(k == room_id){
			   				chk = 'selected';
			   		 	}
			   		}
        	       html += '<option value="'+k+'" '+chk+'>'+ i +'</option>';
        	   });
        	   html += '</optgroup>';
        	});	
		}

        html += '</select>';
        html += '</div>';

		var s2 = (type ==1) ? 'col-md-0' : 'col-md-3';
		var s3 = (type ==1) ? 'width:0px' : '';
		var s4 = (type ==1) ? 'hidden' : 'text';

        html += '<div class="'+s2+'  _change2" style="'+s3+'" >';
        html += '   <input type="'+s4+'" id="flight-num" class="form-control _change_num" required name="room['+num+'][num]" placeholder="入住人数" value='+people+'>';
        html += '</div>';

        html += '<div class="col-md-1">';
        html += '   <button type="button" class="btn btn-danger room-remove">x</button>';
        html += '</div>';

        //$(this).parents(".change-room").after(html);
        $(".change-room").last().after(html);

        $(".select2-add").select2({
            'theme' : 'select2 select2-container select2-container--krajee select2-container--focus',
			'placeholder' : '选择舱房',
        });
	}//}}}

    
    /** 删除选项 */
    $("div").delegate(".room-remove","click",function(){
        $(this).parents(".change-room").remove();

		room_num();
    });



	/** 计算房型选择数量  */	
	function room_num(){//{{{
		var ele = $(".new-room");
		var text = "共计 " + ele.length +" 间";

		var result = new Array();
		var arr = [];
		ele.each(function(i,v){	
				//arr[i] = $(this).data('val');
				result[i] = $(v).data('val');
			});


		result.sort()
		for (var i = 0; i < result.length;) {
			var count = 0;
			for (var j = i; j < result.length; j++) {
				if (result[i] === result[j]) {
					count++;
				}
			}
			//console.log(result[i].indexOf("|"));
			var str = result[i].substr(0, result[i].indexOf("|"));
			arr.push({
				//name: result[i],
				name: str,
				count: count
			})
			i+=count;

		}
		
		for (var k = 0; k < arr.length; k++) {
			//console.log(arr[k].name+ '   ' + arr[k].count)
			text += '&nbsp;&nbsp;&nbsp;&nbsp;|   '+arr[k].name+ '&nbsp;&nbsp;' + arr[k].count + ' 间';
		}

		$("#show-chage-text").html(text);
	}//}}}
	

</script>
<?php app\components\JsBlock::end() ?>
